package com.hzzh.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hzzh.service.EmployeeService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 获得jsp页面请求参数
		String username = request.getParameter("username");
		String password = request.getParameter("pwd");

		// 调用service业务逻辑方法
		EmployeeService service = new EmployeeService();
		int flag;
		try {
			flag = service.login(username, password);
			if (flag == 1) {
				ServletContext ctxt = this.getServletContext();
				int visitcount;
				if (ctxt.getAttribute("visitcount") == null) {
					visitcount = 0;
				} else {
					visitcount = Integer.parseInt(ctxt.getAttribute("visitcount").toString());
				}
				visitcount++;
				ctxt.setAttribute("visitcount", visitcount);
				// 获得会话对象
				HttpSession session = request.getSession();

				// 把登陆成功的员工姓名保存到会话
				session.setAttribute("employeeid", service.getLoginedEmployee().getEmployeeid());
				session.setAttribute("employeename", service.getLoginedEmployee().getEmployeename());

				request.getRequestDispatcher("adminindex.jsp").forward(request, response);

			} else {
				if (flag == 0) {
					request.setAttribute("msg", "正在审核，请耐心等待");
				}
				if (flag == 2) {
					request.setAttribute("msg", "审核未通过，请核实后重新注册");
				}
				if (flag == 3) {
					request.setAttribute("msg", "用户名或密码错误，请重试");
				}
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
		}

		catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
